package krow.dev.gunpobus.control.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import krow.dev.gunpobus.Constants.Attribute;
import krow.dev.gunpobus.Constants.Value;
import krow.dev.gunpobus.model.RouteItem;
import krow.dev.gunpobus.util.CastUtil;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class RouteParser implements IHtmlParser {

	private static Pattern sRouteIdPattern = Pattern.compile("(?:routeId=([0-9]+))");
	private static Pattern sTypePattern = Pattern.compile("(?:ico_bus_([0-9]+)\\.gif)");

	private List<RouteItem> mRouteItemList;
	
	private Map<String, RouteItem> mRouteItemMap;
	
	public RouteParser() {
		
		mRouteItemList = new ArrayList<RouteItem>();
	
		mRouteItemMap = new HashMap<String, RouteItem>();
	}
	
	public List<RouteItem> getRouteItemList(){
		
		return mRouteItemList;
	}
	
	public Map<String, RouteItem> getRouteItemMap(){
		
		return mRouteItemMap;
	}
	
	@Override
	public void parse(Source source) throws Exception {

		List<Element> tableElemeList = source.getAllElements(HTMLElementName.TABLE);
		for (Element tableElement : tableElemeList) {
			if(!Value.CLASS_DATABOX.equals(tableElement.getAttributeValue(Attribute.CLASS))){
				continue;
			}
			
			List<Element> dataElementList = tableElement.getAllElements(HTMLElementName.TD);
			for (Element dataElement : dataElementList) {
				parseRoute(dataElement);
			}
		}
	}

	private void parseRoute(Element element){
		String id = null;
		String name = null;
		int type = 0;
		
		try {
			Matcher matcher = sRouteIdPattern.matcher(element.getAttributeValue(Attribute.CLICK));
			if(matcher.find()){
				id = matcher.group(1);
			}

			List<Element> imageElementList = element.getAllElements(HTMLElementName.IMG);
			for (Element imageElement : imageElementList) {
				matcher = sTypePattern.matcher(imageElement.getAttributeValue(Attribute.SOURCE));
				if(matcher.find()){
					type = CastUtil.toInteger(matcher.group(1));
				}
			}
			
			List<Element> spanElementList = element.getAllElements(HTMLElementName.SPAN);
			for (Element spanElement : spanElementList) {
				
				String className = spanElement.getAttributeValue(Attribute.CLASS);
				
				if(className.equals(Value.CLASS_ROUTE_NAME)){
					name = spanElement.getTextExtractor().toString();
				}
			}
			
		} catch (Exception e) {

		}

		if(id != null){
			RouteItem routeItem = new RouteItem();
			routeItem.setId(id);
			routeItem.setName(name);
			routeItem.setType(type);
			
			mRouteItemList.add(routeItem);
			mRouteItemMap.put(id, routeItem);
		}
	}
}
